package com.imau.common.handler;

import com.alibaba.fastjson.JSON;
import com.imau.common.entiry.ResultCode;
import com.imau.common.entiry.ResultEntity;
import com.imau.common.exception.CommonException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/BaseExceptionHandle")
public class BaseExceptionHandle extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(BaseExceptionHandle.class);
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1
        System.out.println("有异常.....");

        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
        System.out.println("statusCode=" + statusCode);
        System.out.println("servletName=" + servletName);

        logger.error("statusCode="+statusCode+",servletName="+servletName+"异常信息:"+throwable.getMessage());

        //响应结果 ResultEntity 封装
        ResultEntity result = errorHandeler(request,response,throwable);

        response.getWriter().write(JSON.toJSONString(result));


    }


    public ResultEntity errorHandeler(HttpServletRequest request, HttpServletResponse response, Throwable e) {

        if (e.getClass() == CommonException.class) {
            //类型转型
            CommonException ce = (CommonException) e;
            ResultEntity result = new ResultEntity(ce.getResultCode());
            return result;

        } else {

            ResultEntity result = new ResultEntity(ResultCode.SERVER_ERROR);
            return result;
        }
    }

}
